package com.zzgele.qmzb.api.web;

import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.core.Result;
import com.zzgele.qmzb.api.core.ResultGenerator;
import com.zzgele.qmzb.api.model.Sms;
import com.zzgele.qmzb.api.service.SmsService;
import com.zzgele.qmzb.api.utils.DateUtil;
import com.zzgele.qmzb.api.utils.SmsUtil;
import com.zzgele.qmzb.api.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Created by Martin on 2017/07/09.
 */
@RestController
@RequestMapping("/sms")
public class SmsController {
    private final Logger logger = LoggerFactory.getLogger(SmsController.class);
    @DubboConsumer
    private SmsService smsService;

    @PostMapping("/send")
    public Result send(String mobile) {
        logger.info("/send mobile:{}", mobile);

        if (StringUtil.isEmpty(mobile)) {
            return ResultGenerator.genFailResult("请提供手机号码");
        }

        String smsCodeStr = Constants.SMS_CODE_DEF;
        if(!mobile.equals(Constants.TEST_USER_1) && !mobile.equals(Constants.TEST_USER_2)) {
            //if (!Constants.IS_DEBUG) {
            smsCodeStr = StringUtil.getRandomFour();
            //}
        }

        Sms sms = smsService.findBy("mobile", mobile);
        logger.info(smsCodeStr);
        if(sms == null) {
            sms = new Sms();
            sms.setCode(smsCodeStr);
            sms.setMobile(mobile);
            sms.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            smsService.save(sms);
        } else {
            //TODO:检测短信验证码是否过期，如果未过期，不更新验证码
            //TODO:检测短信验证码发送是否超过限制时间周期

            sms.setCode(smsCodeStr);
            sms.setCreateTime(DateUtil.getCurUnixTimeStampInt());
            smsService.update(sms);
        }

        String sendResult = "";
        //sendResult += Constants.IS_DEBUG ? "[" + smsCodeStr + "]" : "";

        //if (!Constants.IS_DEBUG) {
        //Long sms_id = sms.getId();
        Boolean sendFlag = SmsUtil.sendSms(mobile, smsCodeStr);
        if (!sendFlag) {
            return ResultGenerator.genFailResult("短信验证码发送失败，请联系客服");
        }
        //}

        return ResultGenerator.genSuccessResult("短信验证码已发送" + sendResult);
    }
}
